package com.windystory.wslibrary.net;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.windystory.wslibrary.util.LogUtil;

import java.net.Proxy;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Retrofit工具类
 */
public class RetrofitUtil {

    /**
     * 连接超时时间
     */
    private static final int CONNECT_TIMEOUT = 30;
    /**
     * 读取超时时间
     */
    private static final int READ_TIMEOUT = 30;
    /**
     * 写入超时时间
     */
    private static final int WRITE_TIMEOUT = 30;
    /**
     * RetrofitUtil的实例
     */
    private static RetrofitUtil retrofitInstance;
    /**
     * Retrofit
     */
    private static Retrofit retrofit;

    /**
     * OkHttpClient
     */
    private OkHttpClient client;
    private OkHttpClient.Builder OkBuilder;

    /**
     * 初始化retrofit参数
     */
    public RetrofitUtil(String HOST) {
        OkBuilder = new OkHttpClient.Builder();
        if (LogUtil.isDebug) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkBuilder.addInterceptor(logging);
        }
        OkBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        OkBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
        OkBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
        //防止抓包
        OkBuilder.proxy(Proxy.NO_PROXY);
        client = OkBuilder.build();

        retrofit = new Retrofit.Builder()
                .baseUrl(HOST)//设置主机地址
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    }

    /**
     * 获取当前RetrofitUtil实例
     *
     * @return 当前RetrofitUtil实例
     */
    public static RetrofitUtil getInstance(String HOST) {
        return new RetrofitUtil(HOST);
    }

    /**
     * 获取OkhttpClient
     *
     * @return 获取OkhttpClient
     */
    public OkHttpClient getOKHttpClient() {
        return client;
    }

    /**
     * 设置Url类
     *
     * @param cls 定义接口标准的Interface类
     * @param <T> class
     * @return retrofit
     */
    public <T> T createNetWorkStandard(Class<T> cls) {
        return retrofit.create(cls);
    }

}
